/**
 * Created by Administrator on 17-10-12.
 */
var  room=require('./room_d89');
var core_d89=require("./core_d89");
var  iconst=require('./iconst');
core_d89=new core_d89();
var     P = require("bluebird");
var  util=require('./util');
room.prototype.onIdle=function()
{

}

room.prototype.getLeftTime=function()
{
    var  second=this.get('countDownTime');
    var  time=second-(Math.floor((new Date().getTime()-this.get('countDownTick'))/1000));
    if(time<0) time=0;
    return time;
}

room.prototype.getGoingTime=function()
{
    var  time=(Math.floor((new Date().getTime()-this.get('countDownTick'))/1000));
    return time;
}
room.prototype.waitReadyEnd=function()
{
    var  count=0;
    var  list=this.get('userList');
    var  len=list.length;
    for(var i=0;i<len;i++)
    {   var  u=list[i];
        if(u.playing==1)
        { count++;}
        u.bet=0;
        u.zbet=0;//初始化抢庄倍数为0,所有人都没有抢庄
    }
    var  gameType=this.get("gameType");
    var  userMap=this.get("userMap");
    if(gameType==iconst.d89.gameTypeGudingZhuangjia)
    {
        var  bank=userMap[this.get("ownerUid")];
        bank.zbet=1;
        if(bank&&bank.playing!=1)
        {   //console.logr(this.roomPsw,'固定庄家模式，庄家没有准备游戏不能开始');
            //this.changeState('waitReady');
            //this.notifyUpdate();
            return;
        }
    }

    if(count<2)
    {    //console.logr(this.roomPsw,'玩家还没准备好继续等待');
        this.notifyUpdate();
        return;
    }
     this.startNewGame();
    var  gameType=this.get("gameType");
    if(gameType==iconst.d89.gameTypeTongbi)
    {
        this.changeState('waitTanpai');
        this.notifyUpdate();
        return;
    }
    if(gameType==iconst.d89.gameTypeGudingZhuangjia)
    {
        this.changeState('waitBetting');
        this.notifyUpdate();
        return;
    }
     this.changeState('waitQiangzhuang');
    this.notifyUpdate();
}

room.prototype.waitBettingEnd=function()
{
    this.changeState('waitTanpai');
    this.notifyUpdate();
}

room.prototype.waitTanpaiEnd=function()
{
    this.changeState('showGameResult');
    this.notifyUpdate();
    this.gameOver();
}

room.prototype.waitQiangzhuangEnd=function()
{
    var  bankUid=this.get('bankUid');
    if(bankUid!=-1) { console.logr(this.roomPsw,'已经选出庄家了不能重复',bankUid);return;}
    var  count=0;
    var  m=0;
    var  list=this.get('userList');
    var  len=list.length;
    var  alist=[];
    for(var i=0;i<len;i++)
    {   var user=list[i];
        if(user.playing==1)
        { alist.push(user); }
    }
    alist.sort(function(a,b)
    { return b.zbet- a.zbet;});
    var  index=0;
    var  blist=[alist[0]];
    var  len=alist.length;
    for(var i=1;i<len;i++)
    {
        if(alist[i].zbet==alist[0].zbet)
            blist.push(alist[i]);
    }
    var  len1=blist.length;
    if(len1>0)
    {
        var n=Math.floor(Math.random()*12);
        index=n%len1;
        console.logr(this.roomPsw,len1,'105 随机选择庄家',n,index);
    }
    if(alist[0].zbet==alist[1].zbet)
    {   //var n=Math.floor(Math.random()*10);
        //index=n%2;
        //console.logr(this.roomPsw,'随机选择庄家',index);
    }
    bankUid=blist[index].uid;
    this.set('bankUid',bankUid);
    console.logr(this.roomPsw,'选出庄家',bankUid);
    for(var i=0;i<len;i++)
    {    var user=list[i];
        //if(user.playing==1)
        if(user.gaming==1)
        { if(user.zbet<=0) user.zbet=1;}
    }
    this.changeState('waitBetting');
    this.notifyUpdate();
}
room.prototype.showGameResultEnd=function()
{
    this.changeState('waitReady');
     this.notifyUpdate();
}

room.prototype.showFinalResultEnd=function()
{
    //this.changeState('waitReady');
    console.logr(this.roomPsw,'showFinalResultEnd');
    this.destroyRoom();
}

room.prototype.returnOrnerCard= P.coroutine(function*()
{
    var ownerUid=this.get('ownerUid');
    var cardRequire=this.get('cardRequire');
    console.logr(this.roomPsw,'退还房主房卡 ',ownerUid,cardRequire);
    yield this.userDao.addUserCardNum(ownerUid,cardRequire);

});

room.prototype.decUserCard= P.coroutine(function*(user)
{

    if(user.cardConsume>0)
        return;
    var cardType=this.get('cardType');
    if(user.uid!=this.get('ownerUid'))
    { return; }
    var cardRequire=this.get('cardRequire');
    var info=this.getUserInfo(user.uid);
    info.cardNum-=cardRequire;
    user.cardNum-=cardRequire;
    user.cardConsume=cardRequire;
    console.logr(this.roomPsw,'@#$扣除玩家 ',user.uid,user.name,cardRequire,'房卡 剩余',info.cardNum);
    // yield this.userDao.decCardSafeAsync(user.uid,cardRequire);
    var  today=this.userDao.getLastDay(0);
    //yield this.userDao.incDayCard(user.name,user.uid,today,cardRequire);
    //yield this.userDao.incDayCard('sys','8888',today,cardRequire);
    //yield this.userDao.incDayCard('sys','total','2017-1-1',cardRequire);
});

room.prototype.recordDayConsume= P.coroutine(function*()
{

   console.logr(this.roomPsw,'累加每日消费房卡记录')
    var cardType=this.get('cardType');

    var cardRequire=this.get('cardRequire');
    var  ownerUid=this.get('ownerUid');
    var info=this.getUserInfo(ownerUid);

    //console.logr(this.roomPsw,'@#$扣除玩家 ',user.uid,user.name,cardRequire,'房卡 剩余',info.cardNum);
    // yield this.userDao.decCardSafeAsync(user.uid,cardRequire);
    var  today=this.userDao.getLastDay(0);
    yield this.userDao.incDayCard(info.name,info.uid,today,cardRequire);
    yield this.userDao.incDayCard('sys','8888',today,cardRequire);
    yield this.userDao.incDayCard('sys','total','2017-1-1',cardRequire);
});

room.prototype.startNewGame=function()
{
    var  gamingCount=this.get('gamingCount');
    console.logr(this.roomPsw,'开始新一局游戏',gamingCount);
    this.m['gamingCount']++;
    var  list=core_d89.shuffleCards();
    var  userList=this.get('userList');
    var len=userList.length;
    var  n=0;
    var  activeList=[];
    var  gameType=this.get('gameType');

    for(var i=0;i<len;i++)
    {   var user=userList[i];
        user.zbet=0;user.cuopai=0;
        if(user.gaming==1&&user.playing==1)
        {   user.cards=list[n];
            user.zbet=0;user.tanpai=0;
            //var  cards=core_d89.makeCard(['HEIA','HONG7']);
            //user.cards=cards;
            user.cardItem=core_d89.getCardType(user.cards);
            user.cardsShow=[-1,-1];//用于显示的牌型
            console.logr(this.roomPsw,'给玩家发牌',user.uid,user.name,user.cards[0].name+' '+user.cards[1].name,'seatId=',user.seatId);
            n++;
            activeList.push(user);
        }
        if(user.gaming==1)
        { //this.decUserCard(user);
        }
    }
    var  gamingCount=this.get('gamingCount');
    if(gamingCount==1)
    {
        this.recordDayConsume();
    }
    var  m=activeList.length;
    var  randIndex=Math.floor(Math.random()*m);
    if(randIndex>=m) randIndex=m-1;
    var uid=activeList[randIndex].uid;
    //console.logr(this.roomPsw,'随机产生庄家',uid);
    var  gameType=this.get("gameType");
    if(gameType!=iconst.d89.gameTypeGudingZhuangjia)
        this.set('bankUid',-1);
    else
    {   var  userMap=this.get("userMap");
        var bank=userMap[this.get("bankUid")];
        if(bank)  bank.zbet=1;
    }
    this.extraData={event:'fapai'};
    this.notifyUpdate();
}

room.prototype.calResult=function()
{
    var  gamingCount=this.get('gamingCount');
    if(gamingCount==0)
    {   console.logr(this.roomPsw,"calResult 游戏没有开始不用结算");
        return;
    }

    var  gameCount=this.get('gameCount');
    var  userList=this.get('userList');
    var len=userList.length;
    var   fapaiCount=0;
    for(var i=0;i<len;i++)
    {
        var user=userList[i];
        if(user&&user.cardItem)  fapaiCount++;
    }
    if(fapaiCount==0)
    {
        console.logr(this.roomPsw,"calResult 该局游戏没有发牌不用结算",gamingCount);
        console.logr(this.roomPsw,'游戏最终结算',gamingCount,releaseRoom);
        var  len=userList.length;
        var  result=[];
        for(var i=0;i<len;i++)
        {
            var user=userList[i];
            var item={uid:user.uid,name:user.name,score:user.score,totalBet:user.totalBet};
            result.push(item);
        }
        //result.num=gamingCount;result.sum=gameCount;
        this.m['gameResult'][-1]=result;
        return;
    }
    var  bank=this.getUser(this.get('bankUid'));
    var  typeFanbei=this.get('gameRule');
    var  guestList=[];
    var  diFeng=this.get("diFeng");
    var  releaseRoom=this.get('releaseRoom');
    if(bank) bank.score=0;
    for(var i=0;i<len;i++)
    {  var user=userList[i];
        user.tanpai++;
        if(user.bet==0)  user.bet=1;
        if(user.gaming==1&&user.playing==1)
        {  if(bank&&user.uid==bank.uid)
              {}else
        {   if(user.cardItem)
                guestList.push(user);
        }
        }
        if(user.gaming==1&&user.playing==1)
        {if(!user.cardItem)
        {console.logr(this.roomPsw,"异常,玩家没有牌型数据",user.name,user.uid);
            continue;
        }
            //guestList.push(user);
            var cards=user.cardItem.cards;
            user.cardsShow=[cards[0].cid,cards[1].cid];
        }
    }
    //计算所有玩家跟庄家对比的结果
    var  gameType=this.get("gameType");
    var  len=guestList.length;
    if(len>0)
    {if(gameType!=iconst.d89.gameTypeTongbi)
    {core_d89.compareAllByUser(bank,guestList,typeFanbei);
    bank.totalBet+=bank.score*diFeng;
    }
    else
    {   console.logr(this.roomPsw,"通比模式结算");
        //guestList.push(bank);
        core_d89.TongBi(guestList,typeFanbei);
        var list=guestList.slice();
        var  winner=list[0];
        //winner.score*=diFeng;
        var  score=winner.score;
        var  len=list.length;
        winner.totalBet+=score*(len-1)*diFeng;
        guestList=[];
        for(var i=1;i<len;i++)
        {   var user=list[i];
            user.score=score*-1;
            guestList.push(user);
        }
        bank=winner;
        this.set("bankUid",winner.uid);
    }
    }


    var  len1=guestList.length;
    if(len1>0)
    {
        bank.score*=diFeng;
        var  result=[{uid:bank.uid,name:bank.name,score:bank.score,totalBet:bank.totalBet,zbet:bank.zbet,isBank:1,
        mul:bank.zbet,no_join:0,card:core_d89.cards2List(bank.cardItem.cards),card_code:[bank.cardItem.type]}];
        console.logr(this.roomPsw,"底分",diFeng,'庄家总分',bank.totalBet,'这句赢分',bank.score,bank.uid,bank.name,this.get('gamingCount'));
        console.logr('guestCount ',len1);
        for(var i=0;i<len1;i++)
        {
            var user=guestList[i];
            user.score*=diFeng;
            user.totalBet+=user.score;
            console.logr(this.roomPsw,"底分",diFeng,'玩家总分',user.totalBet,'这句赢分',user.score,user.uid,user.name);
            result.push({uid:user.uid,name:user.name,score:user.score,totalBet:user.totalBet,
                no_join:0,mul:user.bet,
                card:core_d89.cards2List(user.cardItem.cards),card_code:[user.cardItem.type]});
        }
        //没有参与游戏的玩家也记录下
        //var  result=[];
        var  len=userList.length;
        for(var i=0;i<len;i++)
        {   var user=userList[i];
            if(user.playing==1)
                continue;
            var item={uid:user.uid,name:user.name,score:user.score,totalBet:user.totalBet,no_join:1,mul:0};
            result.push(item);
        }

        this.m['gameResult'][gamingCount]=result;
    }

    if(gamingCount==gameCount||releaseRoom==1)
    {
        console.logr(this.roomPsw,'游戏最终结算',gamingCount,releaseRoom);
        var  len=userList.length;
        var  result=[];
        for(var i=0;i<len;i++)
        {
            var user=userList[i];
            var item={uid:user.uid,name:user.name,score:user.score,totalBet:user.totalBet};
            result.push(item);
        }
        //result.num=gamingCount;result.sum=gameCount;
        this.m['gameResult'][-1]=result;
    }
    for(var i=0;i<len;i++)
    {  var user=userList[i];
        if(user.gaming==1)
        { }
       // user.playing=0;
        user.zbet=0;
        //user.cardItem=null;
        user.bet=0;
    }

};
room.prototype.gameOver=function()
{
    var self=this;
    var  doAsync= P.coroutine(function*(self)
    {
        var  releaseRoom=self.get('releaseRoom');
        console.logr(self.roomPsw,'一局游戏结束',self.get('gamingCount'));
        self.calResult();
        var  gamingCount=self.get('gamingCount');
        var  gameCount=self.get('gameCount');
        self.extraData.event='gameOver';
        self.notifyUpdate();
        if(gamingCount==gameCount||releaseRoom==1)
        {   yield self.finalGameOver();
            return;
        }
        var  userList=self.get('userList');
        var len=userList.length;
        for(var i=0;i<len;i++)
        {    var user=userList[i];
            user.playing=0;
            user.cardItem=null;
            user.cardsShow=null;
            user.zbet=0;
            //user.cardItem=null;
            user.bet=0;
        }
    });
    doAsync(self);
}
//桀骜不驯
room.prototype.finalGameOver= P.coroutine(function*()
{
    console.logr(this.roomPsw,'finalGameOver');
    var  gamingCount=this.get('gamingCount');
    if(gamingCount==0)
    {   console.logr(this.roomPsw,'finalGameOver 游戏没有开始过不用记录游戏牌局信息');
        this.changeState('showFinalResult');
        return;
    }
    var  userMap={};
    var  userList=this.get('userList');
    var  userDao=this.roomManage.userDao;
    var  redis=this.roomManage.redis;
    var  len=userList.length;
    this.fn=1;
    for(var i=0;i<len;i++)
    {
        var user=userList[i];
        userMap[user.uid]={uid:user.uid,name:user.name,headimgurl:user.headimgurl,wxNickName:user.wxNickName};
        user.gaming=0;
        user.playing=0;
    }
    var  ownerUid=this.get('ownerUid');
    var    date=new Date();
    var    str=util.tick2DateStr(date.getTime());
    var    startTime=this.get('startTime');
    var  finalResult={userMap:userMap,result:this.get('gameResult')[-1],resultList:this.get('gameResult'),ownerUid:ownerUid,
        roomId:this.roomPsw,datetime:str,startTime:startTime,finishtime:str,num:this.get('gamingCount'),sum:this.get('gameCount'),
        roomInfo:this.roomInfo};
    finalResult.date=str;
    var  s=JSON.stringify(finalResult);
    var  userDao=this.roomManage.userDao;
    var   tick=new Date().getTime();
    var   room_tick=this.roomPsw+'_'+this.get('createTick');
    for(var i=0;i<len;i++)
    {   var user=userList[i];
        yield  userDao.insert_result_d89_Async(user.uid,s,tick,room_tick,ownerUid);
    }
    this.changeState('showFinalResult');
    this.extraData={finalResult:finalResult};
    var   resultRedis={userMap:userMap,result:this.get('gameResult')[-1],ownerUid:this.get('ownerUid'),
    roomId:this.roomPsw,datetime:str,num:this.get('gamingCount'),sum:this.get('gameCount')};
    var  s1=JSON.stringify(resultRedis);
    yield this.finalResult2Redis(s1);
    this.notifyUpdate();
});

//把游戏结果记录到redis中去
room.prototype.finalResult2Redis= P.coroutine(function*(s)
{
    var    redis=this.roomManage.redis;
    var    date=util.getToday();
    var    str=util.tick2DayStr(this.get('createTick'));
    var     key=this.roomPsw+'_'+this.get('createTick');
    console.logr('finalGameOver',this.roomPsw,s);
    yield  redis.setHashItem(str,key,s);
});